###一、递归法与递推法的比较:
- 递归法比递推法速度慢;
- 递归法比递推法适用范围广。
###二、汉诺塔问题分析:
- 1个盘子:直接移动, “N==1”是递归终结条件。
- N个盘子:吧移动N个盘子的问题转化为移动N-1盘子的问题。
(1)把A上面的N-1个盘子移动B(借助C);
(2)把第N个盘子一道C;
(3)把B上的N-1个盘子移到C(借助A)
#include <iostream>
using namespace std;
void hanoi(int N ,char source , char relay ,char destination)
{
if(N == 1)
cout << source << "-->" << destination << endl ;
else
{
hanoi(N-1 , source , destination , relay) ;
cout << source << "-->" << destination << endl ;
hanoi(N-1 , relay , source , destination) ;
}
}
int main()
{
cout << "移动盘子:" << endl ;
hanoi(3, 'A' , 'B' , 'C') ;
return 0;
}
####运行结果: